/**
 * Project: complex.common
 * 
 * File Created at 2010-6-2
 * $Id$
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.ymkyve.complex.common;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:XXX
 * @author gaoliang
 * @date 2010-6-2
 * @version 1.0
 */
class TestBean {
    private String  a;
    private boolean b;

    public String getA() {
        return a;
    }

    public void setA(String a) {
        this.a = a;
    }

    public boolean isB() {
        return b;
    }

    public void setB(boolean b) {
        this.b = b;
    }

}

/**
 * bean转map
 * @description:XXX
 * @author gaoliang
 * @date 2010-6-2
 * @version 1.0
 */
public class BeanToMapUtils {
    @SuppressWarnings("unchecked")
    public static Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Class clazz = obj.getClass();
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null) {
            for (Field field : fields) {
                String name = field.getName();
                String changeName = name.substring(0, 1).toUpperCase() + name.substring(1);
                Method m = null;
                try {
                    m = clazz.getMethod("get" + changeName, new Class[] {});
                } catch (Exception e) {

                }
                if (m == null) {
                    try {
                        m = clazz.getMethod("is" + changeName, new Class[] {});
                    } catch (Exception e) {

                    }
                }

                if (m != null) {
                    try {
                        paramMap.put(name, m.invoke(obj, new Class[] {}));
                    } catch (Exception e) {

                    }
                }
            }
        }
        return paramMap;
    }
    
    public static void main(String[] args) {
        TestBean bean = new TestBean();
        bean.setA("1111");
        bean.setB(true);
        Map map = beanToMap(bean);
        System.out.println(map.toString());
    }
}
